import React, { Component } from 'react'
import { Link } from 'react-router'
import { Tooltip, message, notification, Spin } from 'antd';
import * as pub from '../../config/public'
import * as fetch from '../../config/fetch'
import $ from 'jquery'
import videojs from 'video.js'

let old_time = 0;
let myPlayer;
let waitNum = 0;

class Information extends Component {
    constructor(props) {
        super(props);
        this.state = {
            old_time: 0,
            isEnd: false,
            courseattach: [],
            coursedata: {},
            scoreRecords: {},
            isGoodCourse: true,
            isQuick: false,
            answerScore: '',
            video: {}
        }
    }
    onTimeUpdate(e) {
    	let test = document.getElementById('course_id');
    	if (test.currentTime - old_time > 1) {
    		test.currentTime = old_time;
    	} else {
    		if (test.currentTime >= test.duration) {
    			this.setState({
    				isEnd: true
    			})
    		}
    	}
    	old_time = test.currentTime
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            courseattach: nextProps.courseattach,
            coursedata: nextProps.coursedata,
            scoreRecords: nextProps.scoreRecords,
            isGoodCourse: nextProps.coursedata.goodCourse === '1',
            answerScore: nextProps.answerScore
        }, () => {
            if(this.state.coursedata.coursevideoPath !== undefined){
                this.showVideo();
            }
        })
    }
    
    componentDidMount() {
        $('.video-box').find('video')[0].onwaiting = () => {
            waitNum++;
            if (waitNum === 3) {
                waitNum = 0;
                notification['warning']({
                    message: '提示',
                    description: '您当前网速过慢！',
                });
            }

        }
    }
    operate(id, type) {
        fetch.operateCourse(id, type).then((data) => {
            if (data.result === 'RC100') {
                this.props.show();
                message.success(data.msg, 3);
            } else {
                message.error(data.errMsg, 3);
            }
        }, (res) => {
            pub.reject(res);
        })
    }
    saveVideo(){
        let body = {};
      body.videoPalyId = this.props.videoPalyId;
        body.palyInterWay = '局域网';
        body.palyShowWay = 'PC'
        fetch.saveVideoTimes(body).then(data=>{

        }, (res) => {
            pub.reject(res);
        })
    }
    showVideo() {
        //console.log(this.state.coursedata.coursevideoPath);
        const videoJsOptions = {
            autoplay: true,
            controls: true,
            playsinline: false,
            sources: [{
                src: this.state.coursedata.coursevideoPath,
                type: 'video/mp4'
            }]
        }
        let that = this;
        this.player = videojs(this.refs.course_player, videoJsOptions, function onPlayerReady() {
            myPlayer = this;
            myPlayer.on('timeupdate', () => {
                let currentTime = myPlayer.currentTime();
                let duration = myPlayer.duration();
                if (currentTime - old_time > 1) {
                    message.error('请勿快进视频', 1);
                    myPlayer.currentTime(old_time);
                    return;
                } else {
                    if (currentTime >= duration) {
                        that.setState({
                            isEnd: true
                        })
                        that.saveVideo();
                    }
                }
                old_time = currentTime
            });
            myPlayer.play();
        });
    }
    render() {
        let path = {
            pathname: '/TestOnline',
            state: {
                'course_id': this.props.course_id
            },
        }
        let course = this.state.coursedata;
        let scoreRecords = this.state.scoreRecords;
        let answerScore = this.state.answerScore;
        return (
            <div className="panel-120 bg-FFFFFF box-shadow">
				<div className="video-box">

                  <video
                  width={630}
                  height={375}
                  //poster={require('../../style/images/video-error.png')}
                  ref="course_player"
                  className="video-js"
                  ></video>


{ /*				<video 
					id="course_id"
					src={pub.getFile(course.coursevideoPath)}
					controls="controls"  width="630" height="375"
					onTimeUpdate={(e)=>this.onTimeUpdate(e)}
					preload="auto">
						您的浏览器不支持 video 标签。
					</video>*/ }

				</div>
				<div className="v-info">
					<div className="v-cont">
						<h3>⌈<span>{course.userRealName}</span>⌋<span>{course.courseName}</span></h3>
					</div>
					<div className="enclosure">
						<h3>课程附件</h3>
						<ul>
						    {this.state.courseattach.map((attach, index) => {
                return (
                    <a key={index} download={attach.courseattachUniquene} href={pub.getFile(attach.courseattachUniquene)}>{attach.courseAttrachPath}</a>
                )
            })}
						</ul>
					</div>
					<div className="collect-like">

						<span style={{
                opacity: course.userCourseOperation !== undefined && course.userCourseOperation.isCollection === 1 ? 1 : 0.4
            }} onClick={() => this.operate(course.courseId, 2)}><i className="icon-heart"></i>{course.sumCollection}</span>
						<span style={{
                opacity: course.userCourseOperation !== undefined && course.userCourseOperation.isLike === 1 ? 1 : 0.4
            }} onClick={() => this.operate(course.courseId, 3)}><i className="icon-thumbs-up"></i>{course.sumLike}</span>


					</div>
					{this.state.isGoodCourse ? null :
                <div>
                    {scoreRecords.examScore === 5 ?
                    <a className='btn' style={{
                        backgroundColor: '#ccc',
                        cursor: 'default',
                        marginTop: '50px'
                    }}>您已通过此课程</a>
                    :
                    !this.state.isEnd ?
                        <Tooltip placement="rightTop" title="视频播放完成后答题">
                             <a  className="btn btn-answer" style={{
                            backgroundColor: '#6898bd',
                            cursor: 'default'
                        }} disabled={false}>在线答题</a>
                        </Tooltip>
                        :
                        <Link to={path} className="btn btn-answer">在线答题</Link>
                }
					{
                answerScore === -1 || answerScore === '-1' ? null : <Link to={'/AnswerHistory/' + this.props.course_id} className="btn btn-answer" style={{
                    marginLeft: '30px'
                }}>答题历史</Link>
                }
					</div>}
					
				</div>
			</div>
        )
    }
}
class CourseDetail extends Component {
    constructor(props) {
        super();
        this.state = {
            coursedata: {},
            courseattach: [],
            attachvideo: {},
            titleList: [],
            scoreRecords: {},
            categoriesList: [],
            answerScore: '',
            videoPalyId:''
        }
    }
    componentWillMount() {
        this.show();
    }
    show() {
        pub.loading(this, true);
        fetch.courseDetail(this.props.params.id).then((data) => {
            if (data.result === 'RC100') {
                if(data.hasOwnProperty("vpt")){
                    this.setState({videoPalyId:data.vpt.videoPalyId})
                }else{
                    this.setState({videoPalyId:-1})  
                }
                this.setState({
                    coursedata: data.coursedata,
                    courseattach: data.courseattach ? data.courseattach : [],
                    attachvideo: data.attachvideo,
                    titleList: data.titleList,
                    scoreRecords: data.scoreRecords !== null ? data.scoreRecords : {},
                    categoriesList: data.categoriesList.categoriesList,
                    answerScore: data.answerScore,
                 
                },()=>{
                    if(this.state.coursedata){
                        if(this.state.coursedata.courseConvert===1){
                            message.warning('视频上传中，请稍后再试...', 3);
                            this.show();
                        }else if(this.state.coursedata.courseConvert===2){
                            message.warning('视频上传失败，请联系管理员...', 3);
                            this.show();
                        }
                    }
                })
            } else {
                //message.error(data.errMsg, 3);
            }
            pub.loading(this, false);
        }, (response) => {
            pub.loading(this, false);
            pub.reject(response);
        })
    }
    render() {
        let course = this.state.coursedata;
        return (
            <div className="wrapper bg-F0F4F6 detail">
			 <Spin spinning={this.state.loading} tip="加载中...">
			 <div className="layout clearFix pad-t-20">
			   <Information
            show={this.show.bind(this)}
            coursedata={this.state.coursedata}
            courseattach={this.state.courseattach}
            attachvideo={this.state.attachvideo}
            course_id={this.props.params.id}
            scoreRecords={this.state.scoreRecords}
            answerScore={this.state.answerScore}
            videoPalyId={this.state.videoPalyId}
            />
			   <div className="layout clearFix">
			      <div className="left-layout">
					<div className="panel-95 bg-FFFFFF box-shadow clearFix">
						<div className="course-cont">
							<h3>课程简述</h3>
							<div className="row mar-t-20">
							{/*<Switch condition={course.courseType}>
							    {this.state.categoriesList.map((type, index) => {
					                return (
					                    <Case key={index} value={type.code} ><h3 className="pad-l-20">课程分类：{type.name}</h3></Case>
					                )
            					})}
							    <Default><h3 className="pad-l-20">课程分类:未知</h3></Default>
							</Switch>*/}
							{
								this.state.categoriesList.map((type, index) => {
									return(
										<div key={index}>{course.courseType === type.code?<h3 className="pad-l-20">课程分类：{type.name}</h3>:null}</div>
									)
							})}
								<p>{course.courseDesc === null ? '没有描述' : course.courseDesc }</p>
							</div>
						</div>
					</div>
			         </div>
			         <div className="right-layout">
			           <div className="panel-27 bg-FFFFFF box-shadow">
						<div className="user-info-box" style={{
                marginTop: '0px'
            }}>
							<Link to={'/TeacherDetail/' + course.createUser}>
								<img src={pub.getFile(course.headPath)} alt='head' onError={(e) => pub.headImageError(e)}/>
							</Link>
							<h2 className="mar-t-20">{course.userRealName}</h2>
							<h2>{course.branchOffice}</h2>
						</div>
                        {pub.user.channelId === '4' ?
                 		   <Link to={'/PrivateDialogueTheme/' + course.createUser} style={{display:'block',width:'90px',height:'40px',lineHeight: '40px',textAlign: 'center',margin: '0 auto 20px',backgroundColor: '#005496',color: '#FFFFFF',borderRadius: '5px',WebkitBorderRadius: '5px',MozBorderRadius:'5px'}}>私信Ta</Link>:null}	
					</div>
			        </div>
			    </div>
			    </div>
			    </Spin>
			</div>
        )
    }
}
export default CourseDetail;